package com.run.runbbs.controller;

import com.run.runbbs.common.lang.Result;
import com.run.runbbs.entity.User;
import com.run.runbbs.service.impl.ElasticsearchService;
import com.run.runbbs.service.impl.LikeService;
import com.run.runbbs.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.run.runbbs.util.Constant.ENTITY_TYPE_POST;

@RestController
public class SearchController {
    @Autowired
    private ElasticsearchService elasticsearchService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;

    @GetMapping("/search")
    public Result search(String keyword,int offset) throws IOException {
        //搜索帖子
        List<Map<String, Object>> lists = elasticsearchService.searchPost(keyword, offset, 10);
        for(Map<String,Object> map : lists){
            //将时间戳转换为时间。
            long time= (long) map.get("createTime");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("createTime",simpleDateFormat.format(new Date(time)));
            //添加帖子作者信息
            User user=userService.findSimpleUserById((Integer) map.get("userId"));
            map.put("user",user);
            //添加帖子赞的数量
            long likeCount=likeService.findEntityLikeCount(ENTITY_TYPE_POST,(Integer) map.get("userId"));
            map.put("likeCount",likeCount);
        }
        return Result.success(lists);
    }


}
